package org.misalen.web.restful.util;

import java.security.MessageDigest;
import java.util.Random;

import org.apache.log4j.Logger;

public class TextUtil {

	/**
	 * md5 32位
	 * 
	 * @param s
	 * @return
	 */
	public static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 随机数
	 * 
	 * @param count
	 *            长度
	 * @return
	 */
	public static String getNonceNum(int count) {
		StringBuffer str = new StringBuffer();
		Random random = new Random();
		for (int i = 0; i < count; i++) {
			str.append(random.nextInt(10));
		}
		return str.toString();
	}

	/**
	 * 随机字符串
	 * 
	 * @param count
	 *            长度
	 * @return
	 */
	public static String getNonceStr(int count) {
		char[] radixDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
				'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
		int length = radixDigits.length;
		StringBuffer nonceStr = new StringBuffer();
		for (int i = 0; i < count; i++) {
			Random random = new Random();
			nonceStr.append(radixDigits[random.nextInt(length)]);
		}
		return nonceStr.toString();
	}

	/**
	 * log
	 * 
	 * @param category
	 *            类型
	 * @param log
	 *            内容
	 */
	public static void log(String category, Object log) {
		if (log == null) {
			log = "";
		}
		System.err.println(log);
		Logger logger = Logger.getLogger(category);
		logger.info(log.toString());
	}
}
